package com.streaminggbs.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.streaminggbs.common.base.BaseQueryBean;
import com.streaminggbs.common.base.ErrorCodeException;
import com.streaminggbs.common.base.ReturnBean;
import com.streaminggbs.common.config.StaticConfig;
import com.streaminggbs.entity.*;
import com.streaminggbs.interfaces.*;
import com.streaminggbs.common.job.StreamCheckJob;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMethod;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Api(tags = {"录像计划管理接口"})
@Slf4j
@RestController
@RequestMapping("recordplan")
public class RecordPlanController {

    @Autowired
    private RecordPlanService recordPlanService;
    @Autowired
    private DeviceInfoService deviceInfoService;
    @Autowired
    private DeviceChannelInfoService deviceChannelInfoService;
    @Autowired
    private SysAuthDeptService sysAuthDeptService;
    @Autowired
    private StreamCheckJob streamCheckJob;

    @ApiOperation(value = "获取单条录像计划列表", notes = "获取单条录像计划列表")
    @RequestMapping(value = "listOne", method = {RequestMethod.GET})
    public ResponseEntity<ReturnBean> listOne(
            @ApiParam("设备编号") @RequestParam(required = false, name = "device", defaultValue = "1") String device,
            @ApiParam(value = "国标编码") @RequestParam(value = "channel", required = true) String channel) {
        RecordPlan Info = new RecordPlan();
        try {
            RecordPlan entity = new RecordPlan();
            entity.setDevice(device);
            entity.setChannel(channel);
            RecordPlan selectInfo = recordPlanService.selectByOther(entity);
            if (null != selectInfo) {
                Info = selectInfo;
            }
        } catch (Exception e) {
            log.error("获取计划列表异常!{}", e);
        }
        return new ResponseEntity<>(new ReturnBean(Info), HttpStatus.OK);
    }

    @ApiOperation(value = "获取录像计划列表", notes = "获取录像计划列表")
    @RequestMapping(value = "list", method = {RequestMethod.GET})
    public ResponseEntity<ReturnBean> list(
            @ApiParam(value = "分页参数，从1开始") @RequestParam(value = "page", required = false, defaultValue = "1") int page,
            @ApiParam(value = "分页用") @RequestParam(value = "limit", required = false, defaultValue = "10") int limit,
            BaseQueryBean baseQueryBean) {
        PageInfo<RecordPlan> list = new PageInfo<>();
        try {
            list = recordPlanService.selectPageList(baseQueryBean, page, limit);
        } catch (Exception e) {
            log.error("获取计划列表异常!{}", e);
        }
        return new ResponseEntity<>(new ReturnBean(list), HttpStatus.OK);
    }


    @ApiOperation(value = "添加单个计划列表", notes = "添加单个计划列表")
    @RequestMapping(value = "/saveOne", method = {RequestMethod.POST})
    public ReturnBean saveOne(
            @ApiParam("设备编号") @RequestParam(required = false, name = "device", defaultValue = "1") String device,
            @ApiParam(value = "国标编码") @RequestParam(value = "channel", required = true) String channel,
            @ApiParam(value = "内容") @RequestParam(value = "content", required = true) String content
    ) {
        try {
            //验证计划列表是否已存在
            String[] gbIds = channel.split(",");
            for (String id : gbIds) {
                RecordPlan entity = new RecordPlan();
                entity.setChannel(id);
                RecordPlan oldInfo = recordPlanService.selectByOther(entity);
                if (oldInfo != null) {
                    continue;
                }
                entity.setContent(content);
                recordPlanService.save(entity);
                entity.setUpdateTime(new Date());
                streamCheckJob.saveRecord(entity);
            }
            return new ReturnBean("保存成功");
        } catch (Exception e) {
            log.error("==计划列表管理==添加计划列表报错==", e);
            throw new ErrorCodeException(StaticConfig.SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "添加计划列表", notes = "添加计划列表")
    @RequestMapping(value = "/save", method = {RequestMethod.POST})
    public ReturnBean save(
            @ApiParam(value = "国标编码[{\"gb_id\":xxx,\"type\":xxx}] type值（0机构 1设备 2通道）") @RequestParam(value = "gbId", required = false) String gbId,
            @ApiParam(value = "内容") @RequestParam(value = "content", required = true) String content
    ) {
        try {
            //gbId = "[{\"gb_id\":\"34020000001320000001\",\"type\":1},{\"gb_id\":\"34020000001310000001\",\"type\":2}]";
            //content ="[{\"day\":1,\"times\":[{\"stime\":0,\"etime\":1}]}]";
            log.info("gbId:" + gbId);
            log.info("content:" + content);
            JSONArray jsonArray = JSONArray.parseArray(gbId);
            List<String> hasDealList = new ArrayList<>();
            //验证计划列表是否已存在
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject json = jsonArray.getJSONObject(i);
                int type = json.getIntValue("type");
                //String d_gb_id="";
                if (type == 0) {
                    try {
                        String gb_id = json.getString("gbId");
                        SysAuthDept sysAuthDeptQuery = new SysAuthDept();
                        sysAuthDeptQuery.setGbId(gb_id);
                        sysAuthDeptQuery = sysAuthDeptService.selectByOther(sysAuthDeptQuery);
                        List<SysAuthDept> treeDeptList = sysAuthDeptService.getSelectTreeDeptList(sysAuthDeptQuery.getDeptid());
                        for (SysAuthDept sysAuthDept : treeDeptList) {
                            Example example = new Example(DeviceInfo.class);
                            Example.Criteria criteria = example.createCriteria();
                            criteria.andEqualTo("deptid", sysAuthDept.getDeptid());
                            List<DeviceInfo> list = deviceInfoService.selectByExample(example);
                            for (DeviceInfo deviceInfo : list) {
                                Example example2 = new Example(DeviceChannelInfo.class);
                                Example.Criteria criteria2 = example2.createCriteria();
                                criteria2.andEqualTo("deviceid", deviceInfo.getId());
                                List<DeviceChannelInfo> list2 = deviceChannelInfoService.selectByExample(example2);
                                for (DeviceChannelInfo deviceChannelInfo0 : list2) {
                                    String d_gb_id = deviceInfo.getDevice();//设备gbId
                                    gb_id = deviceChannelInfo0.getChannel();
                                    if(hasDealList.contains(d_gb_id+"_"+gb_id)) {
                                        continue;
                                    }
                                    RecordPlan entity = new RecordPlan();
                                    entity.setChannel(gb_id);
                                    entity.setDevice(d_gb_id);
                                    RecordPlan oldInfo = recordPlanService.selectByOther(entity);
                                    if (oldInfo != null) {
                                        if(!StringUtils.equals(oldInfo.getContent(),content)) {
                                            entity.setContent(content);
                                            entity.setUpdateTime(new Date());
                                            recordPlanService.updateNotNull(entity);
                                            streamCheckJob.saveRecord(entity);
                                        }
                                    } else {
                                        entity.setContent(content);
                                        entity.setCreateTime(new Date());
                                        entity.setUpdateTime(new Date());
                                        recordPlanService.save(entity);
                                        streamCheckJob.saveRecord(entity);

                                    }
                                    hasDealList.add(d_gb_id+"_"+gb_id);
                                }
                            }

                        }
                    } catch (Exception e) {
                        log.error("", e);
                    }

                } else if (type == 1) {
                    try {
                        String device = json.getString("device");
                        DeviceInfo deviceInfo = new DeviceInfo();
                        deviceInfo.setDevice(device);
                        String d_gb_id = device;
                        deviceInfo = deviceInfoService.selectByOther(deviceInfo);
                        //DeviceChannelInfo deviceChannelInfo = new DeviceChannelInfo();
                        //deviceChannelInfo.setDeviceid(deviceInfo.getId());
                        if(deviceInfo!=null) {
                            Example example = new Example(DeviceChannelInfo.class);
                            Example.Criteria criteria = example.createCriteria();
                            criteria.andEqualTo("deviceid", deviceInfo.getId());
                            List<DeviceChannelInfo> list = deviceChannelInfoService.selectByExample(example);
                            for (DeviceChannelInfo deviceChannelInfo0 : list) {
                                String gb_id = deviceChannelInfo0.getChannel();
                                if (hasDealList.contains(d_gb_id + "_" + gb_id)) {
                                    continue;
                                }
                                RecordPlan entity = new RecordPlan();
                                entity.setChannel(gb_id);
                                entity.setDevice(d_gb_id);
                                RecordPlan oldInfo = recordPlanService.selectByOther(entity);
                                if (oldInfo != null) {
                                    if (!StringUtils.equals(oldInfo.getContent(), content)) {
                                        entity.setContent(content);
                                        entity.setUpdateTime(new Date());
                                        recordPlanService.updateNotNull(entity);
                                        streamCheckJob.saveRecord(entity);
                                    }
                                } else {
                                    entity.setContent(content);
                                    entity.setCreateTime(new Date());
                                    entity.setUpdateTime(new Date());
                                    recordPlanService.save(entity);
                                    streamCheckJob.saveRecord(entity);
                                }
                                hasDealList.add(d_gb_id + "_" + gb_id);
                            }
                        }
                    } catch (Exception e) {
                        log.error("", e);
                    }
                } else if (type == 2) {
                    try {
                        String gb_id = json.getString("channel");
                        String d_gb_id = json.getString("device");
                        RecordPlan entity = new RecordPlan();
                        entity.setChannel(gb_id);
                        entity.setDevice(d_gb_id);
                        if(hasDealList.contains(gb_id)) {
                            continue;
                        }
                        RecordPlan oldInfo = recordPlanService.selectByOther(entity);
                        if (oldInfo != null) {
                            if(!StringUtils.equals(oldInfo.getContent(),content)) {
                                entity.setId(oldInfo.getId());
                                entity.setContent(content);
                                entity.setUpdateTime(new Date());
                                recordPlanService.updateNotNull(entity);
                                streamCheckJob.saveRecord(entity);
                            }
                        } else {
                            entity.setContent(content);
                            entity.setCreateTime(new Date());
                            entity.setUpdateTime(new Date());
                            recordPlanService.save(entity);
                            streamCheckJob.saveRecord(entity);
                        }
                        hasDealList.add(d_gb_id+"_"+gb_id);
                    } catch (Exception e) {
                        log.error("", e);
                    }
                }
            }
            return new ReturnBean("保存成功");
        } catch (Exception e) {
            log.error("==计划列表管理==添加计划列表报错==", e);
            throw new ErrorCodeException(StaticConfig.SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "删除单个计划列表", notes = "删除单个计划列表")
    @RequestMapping(value = "/deleteOne", method = {/*RequestMethod.GET, */RequestMethod.POST})
    public ReturnBean deleteOne(
            @ApiParam(value = "国标编码[{\"gb_id\":xxx,\"type\":xxx}]") @RequestParam(value = "device", required = false) String device,
            @ApiParam(value = "编码") @RequestParam(value = "channel", required = true) String channel
    ) {
        log.info("======删除gbId计划======>gbIdchannel + channel");
        try {
            RecordPlan recordPlan = new RecordPlan();
            recordPlan.setChannel(channel);
            recordPlanService.delete(recordPlan);
            streamCheckJob.removeRecord(device,channel);
            return new ReturnBean("保存成功");
        } catch (Exception e) {
            log.error("==计划列表管理==删除计划列表报错==", e);
            throw new ErrorCodeException(StaticConfig.SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "删除计划列表", notes = "删除计划列表")
    @RequestMapping(value = "/delete", method = {RequestMethod.POST})
    public ReturnBean delete(
            @ApiParam(value = "国标编码[{\"gb_id\":xxx,\"type\":xxx}]") @RequestParam(value = "gbId", required = false) String gbId
    ) {
        try {
            //gbId ="[{\"gb_id\":\"34020000001310000012\",\"type\":2}]";
            JSONArray jsonArray = JSONArray.parseArray(gbId);
            //验证计划列表是否已存在
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject json = jsonArray.getJSONObject(i);
                int type = json.getIntValue("type");

                if (type == 0) {
                    try {
                        String deptGbID = json.getString("gbId");
                        SysAuthDept sysAuthDeptQuery = new SysAuthDept();
                        sysAuthDeptQuery.setGbId(deptGbID);
                        sysAuthDeptQuery = sysAuthDeptService.selectByOther(sysAuthDeptQuery);
                        List<SysAuthDept> treeDeptList = sysAuthDeptService.getSelectTreeDeptList(sysAuthDeptQuery.getDeptid());
                        for (SysAuthDept sysAuthDept : treeDeptList) {
                            Example example = new Example(DeviceInfo.class);
                            Example.Criteria criteria = example.createCriteria();
                            criteria.andEqualTo("deptid", sysAuthDept.getDeptid());
                            List<DeviceInfo> list = deviceInfoService.selectByExample(example);
                            for (DeviceInfo deviceInfo : list) {
                                String d_gb_id = deviceInfo.getDevice();
                                Example example2 = new Example(DeviceChannelInfo.class);
                                Example.Criteria criteria2 = example2.createCriteria();
                                criteria2.andEqualTo("deviceid", deviceInfo.getId());
                                List<DeviceChannelInfo> list2 = deviceChannelInfoService.selectByExample(example2);
                                for (DeviceChannelInfo deviceChannelInfo0 : list2) {
                                    String gb_id = deviceChannelInfo0.getChannel();
                                    RecordPlan entity = new RecordPlan();
                                    entity.setChannel(gb_id);
                                    recordPlanService.delete(entity);
                                    streamCheckJob.removeRecord(d_gb_id,gb_id);
                                }
                            }

                        }
                    } catch (Exception e) {
                        log.error("", e);
                    }

                } else if (type == 1) {
                    try {
                        String d_gb_id = json.getString("device");
                        DeviceInfo deviceInfo = new DeviceInfo();
                        deviceInfo.setDevice(d_gb_id);
                        deviceInfo = deviceInfoService.selectByOther(deviceInfo);
                        DeviceChannelInfo deviceChannelInfo = new DeviceChannelInfo();
                        deviceChannelInfo.setDeviceid(deviceInfo.getId());
                        Example example = new Example(DeviceChannelInfo.class);
                        Example.Criteria criteria = example.createCriteria();
                        criteria.andEqualTo("deviceid", deviceInfo.getId());
                        List<DeviceChannelInfo> list = deviceChannelInfoService.selectByExample(example);
                        for (DeviceChannelInfo deviceChannelInfo0 : list) {
                            String gb_id = deviceChannelInfo0.getChannel();
                            RecordPlan entity = new RecordPlan();
                            entity.setChannel(gb_id);
                            recordPlanService.delete(entity);
                            streamCheckJob.removeRecord(d_gb_id,gb_id);
                        }
                    } catch (Exception e) {
                        log.error("", e);
                    }
                } else if (type == 2) {
                    try {
                        String channel = json.getString("channel");
                        String device = json.getString("device");
                        RecordPlan entity = new RecordPlan();
                        entity.setChannel(channel);
                        entity.setDevice(device);
                        recordPlanService.delete(entity);
                        streamCheckJob.removeRecord(device,channel);
                    } catch (Exception e) {
                        log.error("", e);
                    }
                }
            }
            return new ReturnBean("保存成功");
        } catch (Exception e) {
            log.error("==计划列表管理==删除计划列表报错==", e);
            throw new ErrorCodeException(StaticConfig.SYSTEM_ERROR);
        }
    }
}
